import {
    globalLayer
} from '../BQGIS-globalVar'

export const symbolConfig = {
    point: {
        pixelSize: 10, // 像素大小
        color: "#3388ff", // 颜色
        opacity: 1, // 透明度
        outline: false, // 	是否边框
        outlineColor: "#ffffff", // 边框颜色
        outlineWidth: 2, // 边框宽度
        heightReference: "NONE", // 指定从实体位置到它的相对高度
    },
    polyline: {
        width: 10, // 线宽
        color: "#3388ff", // 颜色
        opacity: 1, // 透明度
        outline: false, // 	是否边框
        outlineColor: "#ffffff", // 边框颜色
        outlineWidth: 2, // 边框宽度
        fill: true, // 是否填充
    },
    polygon: {
        color: "#3388ff", // 颜色
        opacity: 1, // 透明度
        outline: false, // 	是否边框
        outlineColor: "#ffffff", // 边框颜色
        outlineWidth: 1, // 边框宽度
        heightReference: "NONE", // 指定从实体位置到它的相对高度
        fill: true, // 是否填充
    },
    box: {
        heading: 0, //航向
        pitch: 0, //俯仰
        roll: 0, //横滚
        color: "#00FF00", // 填充颜色
        opacity: 1.0, // 透明度
        outline: false, // 	是否边框
        outlineColor: "#ffffff", // 边框颜色
        heightReference: "NONE", // 指定从实体位置到它的相对高度
        dimensions_x: 100,
        dimensions_y: 100,
        dimensions_z: 100,
        fill: true
    },
    cylinder: {
        heading: 0, //航向
        pitch: 0, //俯仰
        roll: 0, //横滚
        color: "#00FF00", // 填充颜色
        opacity: 1.0, // 透明度
        outline: false, // 	是否边框
        outlineColor: "#ffffff", // 边框颜色
        heightReference: "NONE", // 指定从实体位置到它的相对高度
        topRadius: 100, // 	顶部半径
        bottomRadius: 100, // 底部半径
        length: 100, // 高
        fill: true
    },
    ellipsoid: {
        heading: 0, //航向
        pitch: 0, //俯仰
        roll: 0, //横滚
        color: "#00FF00", // 填充颜色
        opacity: 1.0, // 透明度
        outline: false, // 	是否边框
        outlineColor: "#ffffff", // 边框颜色
        heightReference: "NONE", // 指定从实体位置到它的相对高度。
        radii_x: 100, // X半径
        radii_y: 100, // Y半径
        radii_z: 100, // Z半径
        fill: true
    },
    model: {
        heading: 0, //航向
        pitch: 0, //俯仰
        roll: 0, //横滚
        color: "#FFFFFF", // 填充颜色
        heightReference: "NONE", // 指定从实体位置到它的相对高度。
        url: "", // 模型地址
        scale: 1, // 比例
        colorBlendMode: "HIGHLIGHT",
        fill: true
    }
}

export const symbolTypes = [{
        value: "point",
        label: "点"
    }, {
        value: "polyline",
        label: "折线"
    }, {
        value: "polygon",
        label: "面"
    }, {
        value: "box",
        label: "长方体"
    },
    {
        value: "cylinder",
        label: "圆锥"
    },
    {
        value: "ellipsoid",
        label: "球体"
    },
    {
        value: "model",
        label: "模型"
    }
]

export const propertyOption = {
    colorBlendModeOptions: [{
            value: "HIGHLIGHT",
            label: "将源颜色乘以目标颜色"
        },
        {
            value: "REPLACE",
            label: "将源颜色替换为目标颜色"
        },
        {
            value: "MIX",
            label: "将源颜色和目标颜色混合在一起"
        }
    ],
    heightReferenceOptions: [{
            value: "NONE",
            label: "位置绝对"
        },
        {
            value: "CLAMP_TO_GROUND",
            label: "位置固定在地形上"
        },
        {
            value: "RELATIVE_TO_GROUND",
            label: "位置高度是指地形上方的高度"
        }
    ],
    horizontalOriginOptions: [{
            value: "CENTER",
            label: "原点在对象的水平中心"
        },
        {
            value: "LEFT",
            label: "原点在对象的左侧"
        },
        {
            value: "RIGHT",
            label: "原点在对象的右侧"
        }
    ],
    verticalOriginOptions: [{
            value: "CENTER",
            label: "原点在对象的垂直中心"
        },
        {
            value: "BOTTOM",
            label: "原点在对象的底部"
        },
        {
            value: "BASELINE",
            label: "如果对象包含文本，则原点位于文本的基线，否则原点位于对象的底部"
        },
        {
            value: "TOP",
            label: "原点在对象的顶部"
        }
    ]
}


export function loadEntity(data, viewer = window.viewer, graphicLayer) {
    const graphic = mars3d.GraphicUtil.create(data.type, {
        position: data.position,
        style: format(data.style, data.type)
    })
    if (graphicLayer) {
        graphicLayer.addGraphic(graphic)
    } else {
        viewer.graphicLayer.addGraphic(graphic)
    }
    return graphic
}

export function changeEntityStyle(entity, obj) {
    if (!entity) return
    entity.setStyle(format(obj, entity.type))
}

// 设置相机锁定模型
export function tracked(viewer, entities) {
    viewer.trackedEntity = entities
}

export function startDraw(data, viewer = window.viewer) {
    setSymbolGraphicLayer()
    if (data.type === 'point' || data.type === 'polyline' || data.type === 'polygon') {
        globalLayer.symbolLayer.startDraw(data)
    } else {
        if (!viewer.symbolHandler) {
            viewer.symbolHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        }
        viewer.symbolHandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
        viewer.symbolHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
        viewer.symbolHandler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK)
        viewer.symbolHandler.setInputAction((event) => {
            viewer.openSmallTooltip(event.endPosition, '左键单击地图创建模型，右键结束创建')
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
        viewer.symbolHandler.setInputAction(event => {
            const earthPosition = viewer.scene.globe.depthTestAgainstTerrain ? viewer.scene.pickPosition(event.position) : viewer.camera.pickEllipsoid(event.position, viewer.scene.globe.ellipsoid);
            const graphic = loadEntity({
                type: data.type,
                position: earthPosition,
                style: data.style,
            }, viewer, globalLayer.symbolLayer)

        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

        viewer.symbolHandler.setInputAction(event => {
            viewer.symbolHandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
            viewer.symbolHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
            viewer.symbolHandler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK)
            viewer.closeSmallTooltip()
            if (data.success) {
                data.success()
            }
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
    }
}

export function endDraw(viewer) {
    if (!viewer.symbolHandler) return
    viewer.symbolHandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    viewer.symbolHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
    viewer.symbolHandler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK)
    viewer.closeSmallTooltip()
}

function format(obj, type) {
    const property = {}
    for (let key in obj) {
        if (key === 'heightReference') {
            property[key] = obj[key] ? Cesium.HeightReference[obj[key]] : Cesium.HeightReference.NONE
        } else if (key === 'colorBlendMode') {
            property[key] = obj[key] ? Cesium.ColorBlendMode[obj[key]] : Cesium.ColorBlendMode.HIGHLIGHT
        } else if (['dimensions_x', 'dimensions_y', 'dimensions_z', 'heading', 'pitch', 'roll', 'opacity'].indexOf(key) !== -1) {
            property[key] = Number(obj[key]) || 0
        }
        // else if (key === 'color') { // 为了解决给模型添加颜色的bug(模型之间的颜色相互混淆)，加上后可以解决混淆的问题，但是geojson序列化会报错
        //     if (type === 'model') {
        //         property[key] = {
        //             ...Cesium.Color.fromCssColorString(obj[key])
        //         }
        //     } else {
        //         property[key] = obj[key]
        //     }
        // }
        else {
            property[key] = obj[key]
        }
    }
    return JSON.parse(JSON.stringify(property))
}

export function setSymbolGraphicLayer(viewer = window.viewer) {
    if (globalLayer.symbolLayer) return
    globalLayer.symbolLayer = new mars3d.layer.GraphicLayer()
    viewer.addLayer(globalLayer.symbolLayer)
    globalLayer.symbolLayer.bindContextMenu([{
            text: "开始编辑对象",
            show: function (e) {
                const graphic = e.graphic
                if (!graphic || !graphic.hasEdit) {
                    return false
                }
                return !graphic.isEditing
            },
            callback: (e) => {
                const graphic = e.graphic
                if (!graphic) {
                    return false
                }
                if (graphic) {
                    globalLayer.symbolLayer.startEditing(graphic)
                }
            }
        },
        {
            text: "停止编辑对象",
            show: function (e) {
                const graphic = e.graphic
                if (!graphic || !graphic.hasEdit) {
                    return false
                }
                return graphic.isEditing
            },
            callback: (e) => {
                const graphic = e.graphic
                if (!graphic) {
                    return false
                }
                if (graphic) {
                    globalLayer.symbolLayer.stopEditing()
                }
            }
        },
        {
            text: "删除",
            callback: (e) => {
                const graphic = e.graphic
                if (graphic) {
                    graphic.remove()
                }
            }
        }
    ])
}


export function getGeoJson(viewer = window.viewer) {
    setSymbolGraphicLayer(viewer)
    return globalLayer.symbolLayer.toGeoJSON()
}

export function loadGeoJSON(geojson, viewer = window.viewer) {
    setSymbolGraphicLayer(viewer)
    globalLayer.symbolLayer.loadGeoJSON(geojson)
}


export function download(content, filename) {
    const element = document.createElement('a');
    element.setAttribute('download', filename);
    element.style.display = 'none';
    // 字符内容转变成blob地址
    var blob = new Blob([JSON.stringify(content)]);
    element.href = URL.createObjectURL(blob);
    // 触发点击
    document.body.appendChild(element);
    element.click();
    // 然后移除
    document.body.removeChild(element);
};


export function getFileData(e) {
    return new Promise((resolve, reject) => {
        const files = e.target.files;
        if (!files || !files.length) return;
        const file = files[0];
        const reader = new FileReader();
        reader.readAsText(file);
        reader.onload = function () {
            resolve(reader.result)
        };
        reader.onerror = function () {
            reject()
        }
    })
}

export function clearGraphicLayer(viewer = window.viewer) {
    setSymbolGraphicLayer(viewer)
    globalLayer.symbolLayer.clear(true)
}